﻿function OpenDialogGalleryViewItem(strPageURL) {
    var options = {
        url: strPageURL,
    };
    SP.UI.ModalDialog.showModalDialog(options);
}

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = decodeURIComponent(hash[1]);
    }
    return vars;
}

function stringToBoolean(string) {
    switch(string.toLowerCase()) {
        case "true": case "yes": case "1": return true;
        case "false": case "no": case "0": case null: return false;
        default: return Boolean(string);
    }
}

//Init vars
var queryString = getUrlVars();

var numthumbs = queryString["NumThumbs"];
if (numthumbs == null) {
    numthumbs = 15;
}
numthumbs = parseInt(numthumbs);
var maxpagestoshow = queryString["MaxPagesToShow"];
if (maxpagestoshow == null) {
    maxpagestoshow = 7;
}
maxpagestoshow = parseInt(maxpagestoshow);
var enabletoppager = queryString["EnableTopPager"];
if (enabletoppager == null) {
    enabletoppager = true;
}
else {
    enabletoppager = stringToBoolean(enabletoppager);
}

var enablebottompager = queryString["EnableBottomPager"];
if (enablebottompager == null) {
    enablebottompager = true;
}
else {
    enablebottompager = stringToBoolean(enablebottompager);
}

var autostart = queryString["AutoStart"];
if (autostart == null) {
    autostart = false;
}
else {
    autostart = stringToBoolean(autostart);
}
//var enabledownload = queryString["EnableDownload"];
//if (enabledownload == null) {
//    enabledownload = true;
//}
//else {
//    enabledownload = stringToBoolean(enabledownload);
//}

var displaypicturetitle = queryString["DisplayPictureTitle"];
if (displaypicturetitle == null) {
    displaypicturetitle = true;
}
else {
    displaypicturetitle = stringToBoolean(displaypicturetitle);
}

var displaypicturedescription = queryString["DisplayPictureDescription"];
if (displaypicturedescription == null) {
    displaypicturedescription = true;
}
else {
    displaypicturedescription = stringToBoolean(displaypicturedescription);
}

var delay = queryString["Delay"];
if (delay == null) {
    delay = 2500;
}
delay = parseInt(delay);
var defaulttransitionduration = queryString["DefaultTransitionDuration"];
if (defaulttransitionduration == null) {
    defaulttransitionduration = 900;
}
defaulttransitionduration = parseInt(defaulttransitionduration);
var preloadahead = queryString["PreloadAhead"];
if (preloadahead == null) {
    preloadahead = true;
}
else {
    preloadahead = stringToBoolean(preloadahead);
}

var synctransitions = queryString["SyncTransitions"];
if (synctransitions == null) {
    synctransitions = true;
}
else {
    synctransitions = stringToBoolean(synctransitions);
}

var onmouseoutopacity = queryString["OnMouseOutOpacity"];
if (onmouseoutopacity == null) {
    onmouseoutopacity = "0.6";
}
var mouseoveropacity = queryString["MouseOverOpacity"];
if (mouseoveropacity == null) {
    mouseoveropacity = "1.0";
}

var cssFile = queryString["CustomCss"];
if (cssFile != null) {
    $('<link>').appendTo('head').attr({
        rel: 'stylesheet',
        type: 'text/css',
        href: cssFile
    });
}


// This function is executed after the DOM is ready and SharePoint scripts are loaded
// Place any code you want to run when Default.aspx is loaded in this function
// The code creates a context object which is needed to use the SharePoint object model
function sharePointReady() 
{
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Pictures Gallery');
    
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query></Query></View>');
    this.collListItem = oList.getItems(camlQuery);
        
    clientContext.load(collListItem, 'Include(Title, Description, FileLeafRef, File, EncodedAbsThumbnailUrl)');
        
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));   
}

function onQuerySucceeded(sender, args) 
{
    var allItems = '';

    var listItemEnumerator = collListItem.getEnumerator();
    while (listItemEnumerator.moveNext()) 
    {
        var oListItem = listItemEnumerator.get_current();
        var itemTitle = oListItem.get_item('Title');
        var itemDescription = oListItem.get_item('Description');
        var itemName = oListItem.get_item('FileLeafRef');
        var itemPictureUrl = oListItem.get_file().get_serverRelativeUrl();
        var itemThumbUrl = oListItem.get_item('EncodedAbsThumbnailUrl');
        
        if (!itemTitle) {
            itemTitle = itemName;
        }
        if (!itemDescription) {
            itemDescription = ' ';
        }

        var itemHtml = '<li>' +
                       '<a class="thumb" href="' + itemPictureUrl + '" title="' + itemTitle + '">' +
                           '<div class="imgcontainer">' +
                               '<img src="' + itemThumbUrl + '" alt="' + itemTitle + '"/>' +
                           '</div>' +
                       '</a>' +
                       '<div class="caption">' +
                           '<div class="actionsbuttons">';

        //if (enabledownload == true) {
        //    itemHtml += '<div class="download">' + '<a href="' + itemPictureUrl + '" target="_blank" class="mydownload">Download</a>' + '</div>';
        //}

        itemHtml += '</div>';

        if (displaypicturetitle == true) {
            itemHtml += '<div class="image-title">' + itemTitle + '</div>';
        }

        if (displaypicturedescription == true) {
            itemHtml += '<div class="image-desc">' + itemDescription + '</div>';
        }

        itemHtml += '</div></li>';

        allItems += itemHtml;
    }

    $('.thumbs').append(allItems);

    itemsReady();
}

function onQueryFailed(sender, args) 
{
    var errorMessage = 'Request failed. ' + args.get_message() + '\n' + args.get_stackTrace();
    $('.picturesgallery').append(errorMessage);
}

function itemsReady() {
    // We only want these styles applied when javascript is enabled
    $('div.picturesgallery').css({ 'background-image': 'none' });
    $('div.picturesgallery div.navigation').css({ 'width': '300px', 'float': 'left' });
    $('div.picturesgallery div.content').css('display', 'block');
    
    // Initially set opacity on thumbs and add
    // additional styling for hover effect on thumbs
    var onMouseOutOpacity = onmouseoutopacity;
    $('div.picturesgallery #thumbs ul.thumbs li').opacityrollover({
        mouseOutOpacity: onMouseOutOpacity,
        mouseOverOpacity: mouseoveropacity,
        fadeSpeed: 'fast',
        exemptionSelector: '.selected'
    });

    // Initialize Advanced Galleriffic Gallery
    var gallery = $('div.picturesgallery #thumbs').galleriffic({
        delay: delay,
        numThumbs: numthumbs,
        preloadAhead: preloadahead,
        enableTopPager: enabletoppager,
        enableBottomPager: enablebottompager,
        maxPagesToShow: maxpagestoshow,
        imageContainerSel: 'div.picturesgallery #slideshow',
        controlsContainerSel: 'div.picturesgallery #controls',
        captionContainerSel: 'div.picturesgallery #caption',
        loadingContainerSel: 'div.picturesgallery #loading',
        renderSSControls: true,
        renderNavControls: true,
        playLinkText: 'Play SlideShow',
        pauseLinkText: 'Pause SlideShow',
        prevLinkText: 'Previous',
        nextLinkText: 'Next',
        nextPageLinkText: 'Next',
        prevPageLinkText: 'Previous',
        enableHistory: false,
        autoStart: autostart,
        syncTransitions: synctransitions,
        defaultTransitionDuration: defaulttransitionduration,
        onSlideChange: function (prevIndex, nextIndex) {
            // 'this' refers to the gallery, which is an extension of $('#thumbs')
            this.find('div.picturesgallery ul.thumbs').children()
                        .eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
                        .eq(nextIndex).fadeTo('fast', 1.0);
        },
        onPageTransitionOut: function (callback) {
            this.fadeTo('fast', 0.0, callback);
        },
        onPageTransitionIn: function () {
            this.fadeTo('fast', 1.0);
        }
    });

    /**** Functions to support integration of galleriffic with the jquery.history plugin ****/

    // PageLoad function
    // This function is called when:
    // 1. after calling $.historyInit();
    // 2. after calling $.historyLoad();
    // 3. after pushing "Go Back" button of a browser
    //function pageload(hash) {
    //    // alert("pageload: " + hash);
    //    // hash doesn't contain the first # character.
    //    if (hash) {
    //        $.galleriffic.gotoImage(hash);
    //    } else {
    //        gallery.gotoIndex(0);
    //    }
    //}

    // Initialize history plugin.
    // The callback is called at once by present location.hash. 
    //$.historyInit(pageload, "advanced.html");

    //// set onlick event for buttons using the jQuery 1.3 live method
    //$("a[rel='history']").live('click', function (e) {
    //    if (e.button != 0) return true;

    //    var hash = this.href;
    //    hash = hash.replace(/^.*#/, '');

    //    // moves to a new page. 
    //    // pageload is called at once. 
    //    // hash don't contain "#", "?"
    //    $.historyLoad(hash);

    //    return false;
    //});

    /****************************************************************************************/
}
